<template style="height: 100%;">
	<view class="page-container">
		<navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
		<view class="canvas-img">
			<image mode="aspectFit" v-if="canvasPath" :src="canvasPath" lazy-load="true">
			</image>
			<!-- <canvas canvas-id="canvas-ctx" ref="canvasRef" class="cas"
				:style="{ width: canvasW + 'px', height: canvasH + 'px', top: '2220rpx'}"></canvas> -->
			<canvas id="canvas-ctx" class="cas" type="2d"
				:style="{ width: canvasW + 'px', height: canvasH + 'px', top: '2220rpx'}"></canvas>
		</view>
		<view class="footer-new" :class="[isIpx ? 'fix-iphonex-button' : '']">
			<button open-type="share">微信分享</button>
			<button class="save-img" @click='downImg' v-if="writePhotosAlbum">保存图片</button>
			<button class="save-img" @click='handleSetting' v-else>保存图片</button>
		</view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
	</view>
</template>

<script>
	import Painter from "@/utils/painter/index";
	import NavBar from '../../components/common/navbar';
	import api from '@/api/api';
	import Util from '../../utils/filter.wxs'
	import {
		CUSTOMER_INFO
	} from '@/utils/constant';
	import {
		changeToObj
	} from '@/utils/commonActItems.js'
	export default {
		components: {
			navBar: NavBar,
		},
		data() {
			return {
				isShowCustomNavBar: true,
				postImage: '',
				navbarData: {
					showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
					navbarTitle: '分享' //导航栏 中间的标题
				},
				optionInfo: {},
				isIpx: false,
				canvasPath: '',
				screenWidth: '',
				screenHeight: '',
				posterMarginTop: '40rpx',
				logoUrl: 'https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/pdp/logo.png',
				sunBaseCodeUrl: 'https://100000063-1252208446.cos.ap-shanghai.myqcloud.com/images/2022021422750.jpg',
				drawCodeUrl: 'https://100000063-1252208446.file.myqcloud.com/images/飞书20220512-195815.jpg',
				moenyIcon: 'https://100000063-1252208446.file.myqcloud.com/images/ICON/money.jpg',
				lineUrl: 'https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/pdp/line.png',
				canvasW: 310,
				canvasH: 550,
				memberCode: '',
				writePhotosAlbum: true

			}
		},
		onLoad: async function(options) {
			wx.showLoading({
				title: '海报生成中...',
			})
			let params = JSON.parse(decodeURIComponent(options.params))
			this.optionInfo = params

			await this.setfont()
			this.createPosterSunCode()
			let _this = this;
			let activitySwitch = params.activitySwitch
			wx.getSetting({
				complete: res => {
					if (res.authSetting['scope.writePhotosAlbum'] === false) {
						this.writePhotosAlbum = false
					}
				}
			})
		},
		onShow() {
			let systemInfo = uni.getSystemInfoSync();
			let isIpx = systemInfo.model.indexOf('iPhone X') !== -1 || systemInfo.model.indexOf('iPhone1') !== -1 ||
				systemInfo.model.indexOf('unknown<iPhone13') !== -1;
			this.isIpx = isIpx;
			getApp().cl_tracker.track('mini_program_view', {
				path: 'pages/item/itemShare',
				pageName: '分享海报',
			})
		},
		methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
			async setfont() {
        try{
          let a = await wx.loadFontFace({
          	family: 'NotoSansSC-Medium',
          	source: 'url("https://100000063-1252208446.file.myqcloud.com/fonts/revamp/NotoSansSC-Medium.ttf")',
          	scopes: ['webview', 'native'],
          })
          let b = await wx.loadFontFace({
          	family: 'NotoSansSC-Regular',
          	source: 'url("https://100000063-1252208446.file.myqcloud.com/fonts/revamp/NotoSansSC-Regular.ttf")',
          	scopes: ['webview', 'native']
          })
          let c = await wx.loadFontFace({
          	family: 'FrankNew-Medium',
          	source: 'url("https://100000063-1252208446.file.myqcloud.com/fonts/revamp/FrankNew-Medium.otf")',
          	scopes: ['webview', 'native']
          })
          let d = await wx.loadFontFace({
          	family: 'FrankNew-Regular',
          	source: 'url("https://100000063-1252208446.file.myqcloud.com/fonts/revamp/FrankNew-Regular.otf")',
          	scopes: ['webview', 'native']
          })

          return null;
        }catch(e){

          return null
        }
			},
			handleSetting() {
				wx.showModal({
					title: '提示',
					content: '需要您授权保存相册',
					showCancel: false,
					success: modalSuccess => {
						wx.openSetting({
							success: res => {

								if (res.authSetting[
										'scope.writePhotosAlbum']) {
									wx.showModal({
										title: '提示',
										content: '获取权限成功，再次点击下载海报',
										showCancel: false
									})
									this.writePhotosAlbum = true
								} else {
									wx.showModal({
										title: '提示',
										content: '获取权限失败，将无法保存到相册',
										showCancel: false,
									})
								}
							},

						})
					}
				})
			},
			async showPoster(sunCodeUrl) {

				const getImages = [this.optionInfo.url, sunCodeUrl, this.moenyIcon, this.logoUrl, this.lineUrl].map((
					imgSrc) => {
					return new Promise(async (resolve) => {
						const r = await this.getImageInfo({
							imgSrc
						})
						resolve(r)
					})
				})
				const _that = this;
				const [mainPic, sunCodeImage, moneyPic, logoUrl, lineUrl] = await Promise.all(getImages)

				const canvasWidth = 620 / 2;
				const canvasHeight = 1100 / 2;
				const {
					ctx,
					canvas
				} = await this.getCtx()
				const textLeftSpace = 24
				// ctx.save();
				// ctx.beginPath()

				// const painter = new Painter("canvas-ctx", this.$refs.canvasRef, {
				// 	width: canvasWidth,
				// 	height: canvasHeight,
				// });

				// 海报底色(纯白)
				ctx.clearRect(0, 0, canvasWidth, canvasHeight)
				ctx.fillStyle = "#fff";
				ctx.fillRect(0, 0, canvasWidth, canvasHeight);
				ctx.fillStyle = "#FAFAFA";
				ctx.fillRect(0, 0, 310, 314);

				/// 主图
				// const main = canvas.createImage()
				// main.src = mainPic.path;
				// main.onload = () => {
				//     ctx.drawImage(main,20,43,270,270)

				// }
				const main = await this.imgeOnload(mainPic.path, canvas)
				ctx.drawImage(main, 20, 43, 270, 270)
				// logo
				const logo = await this.imgeOnload(logoUrl.path, canvas)
				ctx.drawImage(logo, 91, 20, 128, 28)

				const line = await this.imgeOnload(lineUrl.path, canvas)
				ctx.drawImage(line, 20, 427, 262, 6)

				const sunCode = await this.imgeOnload(sunCodeImage.path, canvas)
				ctx.drawImage(sunCode, 223, 462, 64, 64)

				// // ￥符号+价格
				await this.drawText({
					text: '￥' + Util.moneyFormat(this.optionInfo.price, 2),
					size: 12,
					x: 24,
					y: 392,
					fontWeight: 400,
					fontF: 'FrankNew-Regular',
					color: '#000000',
				}, ctx)

				// // ￥符号+价格
				await this.drawText({
					text: 'THE MACALLAN麦卡伦线上精品店',
					lineHeight: 20,
					y: 462,
					size: 12,
					color: '#000000',
					x: textLeftSpace,
					fontWeight: 400,
					fontF: "NotoSansSC-Regular"
				}, ctx)

				// // 文案
				await this.drawText({
					text: '长按识别二维码',
					size: 10,
					y: 494,
					x: textLeftSpace,
					color: '#757575',
					lineHeight: 16,
					fontF: "NotoSansSC-Regular"
				}, ctx)
				await this.drawText({
					text: '即刻选购',
					size: 10,
					y: 510,
					x: textLeftSpace,
					color: '#757575',
					lineHeight: 16,
					fontF: "NotoSansSC-Regular"
				}, ctx)


				// 标题
				const itemName = this.optionInfo.itemName;
				let tArr = itemName.split('\n')

				const titleWidth = 190

				await this.drawMultipleLine({
						text: tArr[0],
						align: "left",
						lineHeight: 20,
						maxWidth: titleWidth,
						size: 14,
						x: textLeftSpace,
						y: 340,
						line: tArr[1] ? 1 : 2,
						// fontWeight: 500,
						fontF: 'NotoSansSC-Medium,FrankNew-Medium',
						color: "#000"
				},ctx);
				if(tArr[1]) {
					await this.drawMultipleLine( {
							text: tArr[1] || '',
							align: "left",
							lineHeight: 20,
							maxWidth: titleWidth,
							size: 14,
							x: textLeftSpace,
							y: 340 + 20,
							line: 1,
							// fontWeight: 500,
							fontF: 'NotoSansSC-Medium,FrankNew-Medium',
							color: "#000000"
						},ctx);
				}

				uni.canvasToTempFilePath({
					canvas: canvas,
					success(res) {
						_that.canvasPath = res.tempFilePath;
						wx.hideLoading();
					}
				})
				return






				// 标题
				// // const itemName = this.optionInfo.itemName;
				// let tArr = itemName.split('\n')
				// const textLeftSpace = 24
				// const titleWidth = 264;



			},
			imgeOnload(src, canvas) {
				return new Promise((resolve, reject) => {
					let img = canvas.createImage();
					img.src = src
					img.onload = (e) => {
						// ctx.drawImage(img, 20, 43);
						resolve(img);
					};
					img.onerror = (e) => {
						resolve("绘制失败-图片加载失败");
					}
				});
			},
			drawText(e, ctx) {
				return new Promise((resolve) => {
					try {
						const {
							x,
							y,
							text,
							align = "left",
							color = "#000000",
							size = 14,
							baseLine = "top",
							dontRecord,
							fontWeight = "normal",
							fontF = 'sans-serif'
						} = e;
						const lineHeight = e.lineHeight || size;
						const offset = Math.round((lineHeight - size) / 2);
						ctx.font = `${fontWeight} ${size}px  ${fontF}`;
						ctx.fillStyle = color;
						ctx.textAlign = align;
						ctx.textBaseline = baseLine;
						ctx.fillText(text, x, y + offset);

						resolve(true)
					} catch (e) {

						//TODO handle the exception
						resolve()
					}

				});
			},
			async drawMultipleLine(e, ctx) {

				const {
					x,
					y,
					text,
					align = "left",
					color = "#000000",
					size = 14,
					baseLine = "top",
					line,
					maxWidth,
					dontRecord,
					fontWeight,
					fontF = 'sans-serif'
				} = e;
				const lineHeight = e.lineHeight || size;

				let _tmp = "";
				let _curLine = 1;
				const end = "...";
				const len = text.length;
				const _drawText = async (t) => {

					await this.drawText({
						x,
						y: y + (_curLine - 1) * lineHeight,
						color,
						align,
						size,
						baseLine,
						dontRecord: true,
						text: t,
						lineHeight,
						fontWeight,
						fontF
					},ctx);
				};

				for (let i = 0; i < len; i++) {
					const s = text[i];
					const nextText = _tmp + s;
					const nextWidth = ctx.measureText(nextText).width;

					if (_curLine === line) {

						const lastWidth = ctx.measureText(nextText + end).width;
						if (lastWidth > maxWidth) {
							await _drawText(_tmp + end);
							break;
						} else {
							_tmp += s;
							if (i === len - 1) {
								await _drawText(_tmp);
							}
						}
					} else {
						// 非最后一行
						if (nextWidth > maxWidth) {
							await _drawText(_tmp);
							_tmp = s;
							_curLine++;
						} else {
							_tmp += s;
							if (i === len - 1) {
								await _drawText(_tmp);
							}
						}
					}
				}
			},
			getCtx() {
				return new Promise(async (resolve) => {
					uni.createSelectorQuery()
						.select('#canvas-ctx') // 在 WXML 中填入的 id
						.fields({
							node: true,
							size: true
						})
						.exec((res) => {
							// Canvas 对象
							const canvas = res[0].node

							// Canvas 画布的实际绘制宽高
							const renderWidth = 620 / 2
							const renderHeight = 1100 / 2
							// Canvas 绘制上下文
							const ctx = canvas.getContext('2d')

							// 初始化画布大小
							const dpr = wx.getWindowInfo().pixelRatio
							canvas.width = renderWidth * dpr
							canvas.height = renderHeight * dpr
							ctx.scale(dpr, dpr)
							resolve({
								ctx,
								canvas
							})
						})
				})
			},

			//二维码或太阳
			async getImageInfo({
				imgSrc
			}) {
				let _this = this;
				return new Promise((resolve, errs) => {
					uni.getImageInfo({
						src: imgSrc,
						success: function(image) {
							resolve(image);
						},
						fail(err) {
							errs(err);
							wx.hideLoading();
							_this.handleShowTextToast('海报生成失败');
						}
					}, this);
				});
			},
			// 动态生成太阳码
			createPosterSunCode: async function() {
				const that = this;
				let scene = await this.setScence()
				let sharePosterPath = this.optionInfo.sharePosterPath
				let page;
				if (sharePosterPath?.indexOf('?') > 0) {
					page = sharePosterPath.substring(0, sharePosterPath.indexOf('?'))
				} else {
					page = sharePosterPath
				}

				let merchantInfo = uni.getStorageSync('merchantInfo');
				let customerInfo = uni.getStorageSync('customerInfo');
				const result = await api.createSunCode({
					header: {
						jwt: customerInfo.jwt
					},
					method: 'POST',
					query: {
						appId: uni.getAccountInfoSync().miniProgram.appId,
						scene: scene,
						page: page,
						envVersion: api.environment == 'trial' ? 'trial' : 'release',
						outputType: 'file-url'
					}
				});
				if (result.code == 1000) {

					this.showPoster(result.data)
				}
			},

			// 设置自定义海报参数
			setScence: async function() {
				let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || '';
				let query, values;
				let sharePosterPath = this.optionInfo.sharePosterPath
				if (sharePosterPath?.indexOf('?') > 0) {
					query = sharePosterPath.substring(sharePosterPath?.indexOf('?') + 1,
						sharePosterPath.length)
					values = changeToObj(query)
				}
				const sence = await api.setScence({
					method: 'POST',
					query: {
						key: 'sunCode' + '_' + this.optionInfo.goodsId + '_' + this.optionInfo
							.valueId,
						value: JSON.stringify(values)
					},
				})

				if (sence.code === 1000) {

					return sence.data.key
				}
			},
			downImg() {
				const that = this;
				//保存海报图分享
				wx.saveImageToPhotosAlbum({
					filePath: this.canvasPath,
					success: result => {
						that.handleShowTextToast('海报已保存，快去分享给好友吧。')
						this.finishTask()
					},
					fail: err => {

						wx.hideLoading()


					},
				});
			},
			onShareAppMessage: function(res) {
				this.finishTask()
				if (res.from === 'button') {
					// 来自页面内转发按钮

				} else {
					this.$EFSTracking.trackingAction('SHARE_CARD', res.from, {});
				}
				const goodsPath = this.optionInfo.shareCardLink || '/pages/item/item?id=' + this
					.optionInfo.goodsId +
					'&valueId=' + this.optionInfo.valueId +
					'&valueName=' + this.optionInfo.colorName;
				this.$commonSensors.sensorsPageShare()
				this.$sr.setContext({ share_title: this.optionInfo.shareText || 'THE MACALLAN EBOUTIQUE麦卡伦' });
				return this.$commonFunction.commonShare(res, this.optionInfo.shareText, goodsPath, this
					.optionInfo
					.shareCardPicUrl);
			},
			// 完成任务
			finishTask() {
				if (!this.optionInfo.taskCenterCode) {
					return false
				}
				this.posterTrack("微信分享");
				let {
					taskCenterCode,
					taskContentId,
					taskContentName
				} = this.optionInfo
				getApp().finishTask(taskCenterCode, taskContentId, taskContentName, 0)
				setTimeout(() => {
					uni.navigateBack({
						delta: 3
					})
				}, 3000);
			},

			posterTrack(c_area) {
				const goodsPath = this.optionInfo.shareCardLink || '/pages/item/item?id=' + this
					.optionInfo.goodsId +
					'&valueId=' + this.optionInfo.valueId +
					'&valueName=' + this.optionInfo.colorName;
				let name = this.optionInfo.itemName;
				let posterShareParams = {
					"c_area": c_area,
					"c_link_pagename": name,
					"c_link_path": goodsPath
				}
				getApp().commonClTrack("c_ebmp_drawstask_product_poster_share", posterShareParams);
			},
		}
	}
</script>

<style lang="scss">
	.canvas-img {
		position: relative;
		margin: auto;
		display: flex;
		justify-content: center;

		&.fix-iphonex-button {
			margin: 100rpx auto 0;
		}

		.cas {
			background: #fff;
			position: fixed;
			top: -2000rpx;
		}

		image {
			width: 620rpx;
			height: 1100rpx;
		}
	}

	.footer-new {
		// &.fix-iphonex-button {
		// 	height: 120rpx;

		// 	button {
		// 		line-height: 120rpx;
		// 	}

		// 	.save-img {
		// 		line-height: 120rpx;
		// 	}
		// }

		position: fixed;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 32rpx 48rpx 64rpx;
		align-items: center;
		z-index: 9999;
		background-color: #fff;

		button {
			margin: 0;
			width: 320rpx;
			height: 80rpx;
			display: block;
			line-height: 76rpx;
			// background-color: #000;
			font-size: 28rpx;
			box-sizing: border-box;
			border: 2px solid #000000;
			color: #000000 !important;
			background-color: #fff !important;
			padding: 0 !important;
			border-radius: 48rpx 16rpx 48rpx 48rpx;

		}

		// .save-img {
		// 	font-size: 30rpx;
		// 	text-align: center;
		// 	width: 320rpx;
		// 	height: 100%;
		// 	line-height: 100rpx;
		// 	color: #fff;
		// 	background-color: #CB171A;
		// }
	}

	.page-container {
		display: flex;
		justify-content: center;
		background: #ECECEC;
		align-items: center;
		height: 100vh;
	}
</style>
